package com.ctsi.commons.util;


import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;

/**
 * 对字符串进行16进制编码，以在url中传递参数
 * 
 * @author yueming
 *
 */
public class URLencoding {
	/**
	 * 一般字符转为十六进制编码
	 * 
	 * @param str
	 * @return
	 */
	public static String StrToHex(String str) {
		if (UtilValidate.isEmpty(str))
			return str;

		return toHexString(str.getBytes(StandardCharsets.UTF_8));

	}

	/**
	 * 16进制编码转为原始字符串
	 * 
	 * @param hex
	 * @return
	 */
	public static String hexToStr(String hex) {
		if (UtilValidate.isEmpty(hex))
			return hex;

		byte[] temb = fromHexString(hex);
	 
			return new String(temb, StandardCharsets.UTF_8);
 
	}

	public static String toHexString(byte[] bytes) {
		return new String(Hex.encodeHex(bytes));
	}

	public static byte[] fromHexString(String str) {
		str = cleanHexString(str);
		try {
			return Hex.decodeHex(str.toCharArray());
		} catch (DecoderException e) {
			throw new RuntimeException(e);
		}
	}

	public static String cleanHexString(String str) {
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) != 32 && str.charAt(i) != ':') {
				buf.append(str.charAt(i));
			}
		}
		return buf.toString();
	}
}
